Shader "Zoo/StampShader"
{
    Properties
    {
        _MainTex ("Sprite Texture", 2D) = "white" {}
        _TintStrength ("Tint Strength", Range(0,1)) = 0.45
        _Seed ("Seed", Float) = 1.0
    }

    SubShader
    {
        Tags {"Queue"="Transparent" "RenderType"="Transparent"}
        Blend SrcAlpha OneMinusSrcAlpha
        Cull Off
        Lighting Off
        ZWrite Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            sampler2D _MainTex;
            float _TintStrength;
            float _Seed;

            struct appdata {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            float rand(float n) {
                return frac(sin(n) * 43758.5453123);
            }

            float3 pickTint(float seed)
            {
                float r = rand(seed);

                if      (r < 0.16) return float3(1.0, 0.4, 0.4);
                else if (r < 0.32) return float3(0.4, 1.0, 0.4);
                else if (r < 0.48) return float3(0.4, 0.6, 1.0);
                else if (r < 0.64) return float3(1.0, 0.7, 0.2);
                else if (r < 0.80) return float3(0.7, 0.4, 1.0);
                else               return float3(0.2, 1.0, 1.0);
            }

            v2f vert(appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                float2 uv = i.uv;

                float4 col = tex2D(_MainTex, uv);

                if (col.a < 0.01) return col;

                // apply halftone
                float2 h = uv * 300;
                float dots = sin(h.x + h.y * 1.732) * 0.5 + 0.5;
                float intensity = dot(col.rgb, float3(0.333,0.333,0.333));
                float halftone = lerp(intensity, dots, 0.35);

                float3 c = lerp(col.rgb, halftone.xxx, 0.35);

                // desaturate
                float gray = dot(c, float3(0.299, 0.587, 0.114));
                c = lerp(c, gray.xxx, 0.25);

                // retrieve one-color tint
                float3 tint = pickTint(_Seed);

                c = lerp(c, tint, _TintStrength);

                return float4(c, col.a);
            }
            ENDCG
        }
    }
}
